import 'package:dio/dio.dart';

main(List<String> args) async {
  // uploadFile('/home/smqk/图片/author.png');
  // uploadFile('/home/smqk/图片/library.png');

  // List<String> files = List();
  // files.add('/home/smqk/图片/author.png');
  // files.add('/home/smqk/图片/library.png');
  // files.add('/home/smqk/图片/webwxgetmsgimg.png');
  // uploadFiles(files);

  String url = 'http://test.starworking.com:3000/attach/202005/1589190115733_900592_library.png';
  await downloadFile(url, "./download/test.png");


  url = 'https://docs.mongodb.com/manual/_images/agg-pipeline.mp4';
  await downloadFile(url, "./download/agg-pipeline.mp4");


  print('=================  end ==============');
}

/**
 * 单文件上传
 */
uploadFile(String filepath) async {
  var dio = Dio();

  FormData formData =
      FormData.fromMap({"file": await MultipartFile.fromFile(filepath)});
  var response = await dio.post(
    "http://test.starworking.com:3000/qms/upload/uploadAttache",
    data: formData,
  );
  print('文件上传成功， resp: $response');
}

/**
 * 批量上传文件
 */
uploadFiles(List<String> files) async {
  var dio = Dio();

  var formData = FormData();
  formData.files.addAll(
    files.map((v) => MapEntry("file", MultipartFile.fromFileSync(v))),
  );

  var response = await dio.post(
    "http://test.starworking.com:3000/qms/upload/uploadAttache",
    data: formData,
  );
  print('多文件上传成功， resp: $response');
}

/**
 * 文件下载
 */
downloadFile(String url, String savePath) async {
  print('start download ...');

  Dio dio = Dio();
  dio.options.connectTimeout = 5000; //1s
  // dio.options.receiveTimeout = 60000;
  dio.interceptors.add(LogInterceptor());

  await dio.download(url, savePath, onReceiveProgress: showDownloadProgress);
  print("download $url finish");
}


void showDownloadProgress(received, total) {
  if (total != -1) {
    print((received / total * 100).toStringAsFixed(0) + "%");
  }
}